//
//  ARAppleLoginProvider.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/2.
//

import UIKit
import AuthenticationServices

/// 苹果登录
class ARAppleLoginProvider: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    
    enum appleLoginResult {
        case success(token: String)
        case failed(err: Error)
        case cancel
    }
    
    private var callback: ((appleLoginResult) -> Void)? = nil
    
    func startLogin(completion: @escaping (appleLoginResult) -> Void) {
        self.callback = completion
        let provider = ASAuthorizationAppleIDProvider()
        let request = provider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let authorizatioinController = ASAuthorizationController(authorizationRequests: [request])
        authorizatioinController.delegate = self
        authorizatioinController.presentationContextProvider = self
        authorizatioinController.performRequests()
    }
    
    // MARK: - ASAuthorizationControllerDelegate
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // 错误
        debugPrint("苹果登录错误: \(error)")
        if (error as NSError).code == ASAuthorizationError.canceled.rawValue {
            // 取消
            self.callback?(.cancel)
            return
        }
        self.callback?(.failed(err: error))
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        // 成功
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential,
           let tokenData = appleIDCredential.identityToken,
           let tokenStr = String(data: tokenData, encoding: .utf8) {
            // 只要token即可
            self.callback?(.success(token: tokenStr))
        } else {
            self.callback?(.cancel)
        }
    }
    
    // MARK: - ASAuthorizationControllerPresentationContextProviding
    
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return UIApplication.shared.windows.last ?? UIWindow()
    }
}
